﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Kgb.Model.Models;
using Kgb.Service.Repository.Interface;
using System.Runtime.Caching;

namespace Kgb.Service.Repository
{
    public class LocationRepository : ILocationRepository
    {
        private List<Location> _locations;
        private int _nextId;

        public LocationRepository()
        {
            if (MemoryCache.Default["locations"] == null)
            {
                _locations = new List<Location>();
                MemoryCache.Default.Add(new CacheItem("locations", _locations), new CacheItemPolicy() { AbsoluteExpiration = new DateTime(9999, 12, 31) });
            }
            else
            {
                _locations = (List<Location>)MemoryCache.Default["locations"];
            }


            if (_locations.Any())
            {
                _nextId = _locations.Max(c => c.Id) + 1;
            }
            else
            {
                _nextId = 1;

                //inicializa repositório de salas
                RoomRepository _rooms = new RoomRepository();

                foreach(Room room in _rooms.GetAll())
                {
                    for (int i = 1; i <= 6; i++)
                    {
                        this.Add(new Location() { Name = "Posição " + i.ToString(), State = "livre", RoomId = room.Id });
                    } 
                }
            }
        }

        public IQueryable<Location> GetAll()
        {
            return _locations.AsQueryable();
        }

        public IQueryable<Location> GetAllByRoom(int roomId)
        {
            return _locations.Where(s => s.RoomId == roomId).AsQueryable();
        }

        public Location GetByPlayer(Player player)
        {
            return _locations.Where(s => s.LocationPlayer != null && s.LocationPlayer.Equals(player)).FirstOrDefault();
        }

        public Location Get(int id)
        {
            return _locations.Find(c => c.Id == id);
        }

        public Location Add(Location location)
        {
            location.Id = _nextId++;
            _locations.Add(location);
            return location;
        }

        public void Remove(int id)
        {
            Location location = _locations.Find(c => c.Id == id);
            if (location != null)
                _locations.Remove(location);
        }

        public bool Update(Location location)
        {
            int index = _locations.FindIndex(c => c.Id == location.Id);
            if (index == -1)
            {
                return false;
            }
            _locations.RemoveAt(index);
            _locations.Add(location);
            return true;
        }
    }
}